import axios from 'axios'
// import { MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
// import router from '@/router'
// import { removeToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 60000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    // 返回值为附件
    if (response.headers['content-disposition'] && response.headers['content-disposition'].indexOf('attachment') > -1) {
      const res = Object.assign({}, {
        data: response.data,
        contentType: response.headers['content-type'],
        fileName: decodeURIComponent(response.headers['x-attachment'])
      })
      return res
    }

    const res = Object.assign({}, response.data, {
      code: parseInt(response.data.code)
    })

    if (response.config.url === `${process.env.BASE_API}/login`) {
      res.$token = response.headers.authorization
    }

    if (res.code === 403) {
      store.dispatch('LogOut').then(() => {
        location.reload() // 为了重新实例化vue-router对象 避免bug
      })
    }

    if (res.code !== 200) {
      return Promise.reject(res)
    }

    return res
  },
  error => {
    console.log('err', error.response) // for debug
    const response = error.response

    if (!response) {
      return Promise.reject({
        message: '系统出错了（错误代码：5020），请联系管理员'
      })
    }

    if (response.status === 403) {
      store.dispatch('LogOut').then(() => {
        location.reload() // 为了重新实例化vue-router对象 避免bug
      })
    } else if (response.data && response.data.exception && response.data.exception.indexOf('TokenException')) {
      response.data.message = '登录超时或未登录，请重新登录'
      return Promise.reject(response.data)
    } else {
      if (typeof response.data === 'string') {
        response.data = {}
      }
      response.data.message = `系统出错了（错误代码：${response.status}），请联系管理员`
      return Promise.reject(response.data)
    }
  }
)

function createDownlaodRequest(method, url, args, hasData) {
  if (args == null) {
    args = {}
  }

  const config = args.config || {
    headers: args.headers || {}
  }

  config.responseType = 'arraybuffer'

  args.config = config

  return new Promise((resolve, reject) => {
    createRequest(method, url, args, hasData).then(resp => {
      const blob = new Blob([resp.data], {
        type: resp.contentType
      })
      const downloadElement = document.createElement('a')
      const href = URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = resp.fileName // 下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      URL.revokeObjectURL(href) // 释放掉blob对象

      resolve({
        message: 'ok'
      })
    }).catch(resp => {
      reject({
        message: '系统出错了，请联系管理员'
      })
    })
  })
}

function createRequest(method, url, args, hasData) {
  if (args == null) {
    args = {}
  }

  const config = args.config || {
    headers: args.headers || {}
  }
  const params = args.params || args
  delete params.headers
  delete params.config

  if (!hasData) {
    config.params = params
    return service[method](url, config)
  } else {
    // if (config.headers && config.headers['Content-Type'] === consts.H_FORM_DATA['Content-Type']) {
    //   params = Qs.stringify(params)
    // }
    return service[method](url, params, config)
  }
}

Object.assign(service, {
  doGet: (url, args) => {
    return createRequest('get', url, args)
  },

  doDelete: (url, args) => {
    return createRequest('delete', url, args)
  },

  doHhead: (url, args) => {
    return createRequest('head', url, args)
  },

  doPost: (url, args) => {
    return createRequest('post', url, args, true)
  },

  doPut: (url, args) => {
    return createRequest('put', url, args, true)
  },

  doPatch: (url, args) => {
    return createRequest('patch', url, args, true)
  },

  doDownload: (url, args) => {
    return createDownlaodRequest('get', url, args)
  },

  doDownloadByGet: (url, args) => {
    return createDownlaodRequest('get', url, args)
  },

  doDownloadByPost: (url, args) => {
    return createDownlaodRequest('ppst', url, args, true)
  }
})

export default service
